package com.tj.admin.interceptors;

import com.fqgj.exception.common.ApplicationException;
import com.tj.admin.auth.anno.VisitorAccessible;
import com.tj.admin.auth.vo.RequestLocalInfo;
import com.tj.admin.auth.vo.UserAccessInfo;
import com.tj.admin.db.dao.AdminTokenDao;
import com.tj.admin.db.entity.AdminTokenEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @program: binary-option
 * @description
 * @author: binary
 * @create: 2020-06-08 17:00
 **/
@Component
public class AdminAccessInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdminAccessInterceptor.class);


    @Autowired
    private AdminTokenDao adminTokenDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Accept,X-Requested-With,remember-me,bid,basicParams,accessToken");

        //验证token
        String accessToken = request.getHeader("accessToken");
        //异常场景 报错
        HandlerMethod handlerMethod = (HandlerMethod) o;
        VisitorAccessible visitorAccessible = handlerMethod.getMethodAnnotation(VisitorAccessible.class);
        if (visitorAccessible != null) {
            return true;
        }

        if (StringUtils.isEmpty(accessToken)) {
            if (!request.getMethod().equals("OPTIONS")) {
                if (!handlerMethod.getMethod().getName().toUpperCase().equals("LOGIN")) {
                    throw new ApplicationException("need login to access");
                }
            }
        } else {
            AdminTokenEntity adminTokenEntity = adminTokenDao.selectOnByAccessToken(accessToken);
            if (adminTokenEntity == null) {
                throw new ApplicationException("无效的token");
            }

            if (adminTokenEntity.getExpireDate().before(new Date())) {
                throw new ApplicationException("token已失效 请重新登陆");
            }
            UserAccessInfo userAccessInfo = new UserAccessInfo();
            userAccessInfo.setAccessToken(adminTokenEntity.getAccessToken())
                    .setMerchantCode(adminTokenEntity.getMerchantCode());
            RequestLocalInfo.putCurrentUser(userAccessInfo);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object handler, Exception e) throws Exception {
    }

    public AdminAccessInterceptor() {
    }


}
